package top.hkyzf.study.j2se.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author 朱峰
 * @date 2020-12-24 11:30
 */
public class ABADemo {
    // 这里使用 junit 测试会出现线程未走完，就终止的情况
    public static void main(String[] args) {
        AtomicReference<Integer> atomicReference = new AtomicReference<>(100);
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
        }, "T1").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean result = atomicReference.compareAndSet(100, 200);
            System.out.println(result + "\t" + atomicReference.get());
        }, "T2").start();

        System.out.println("=============================================================================");

        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "第一次的版本号：" + atomicStampedReference.getStamp());
            int stamp = atomicStampedReference.getStamp();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicStampedReference.compareAndSet(100, 101,
                    stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName() + "第二次的版本号：" + atomicStampedReference.getStamp());
            atomicStampedReference.compareAndSet(101, 100,
                    atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "第三次的版本号：" + atomicStampedReference.getStamp());

        }, "T3").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "第一次的版本号：" + atomicStampedReference.getStamp());
            int stamp = atomicStampedReference.getStamp();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean result = atomicStampedReference.compareAndSet(100, 101,
                    stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName() + "第二次的版本号：" + atomicStampedReference.getStamp());
            System.out.println(Thread.currentThread().getName() + "修改返回结果为：" + result);
        }, "T4").start();
    }
}
